package com.TinyBBS.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.util.Random;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.TinyBBS.bean.User;
import com.TinyBBS.db.Config;
import com.TinyBBS.model.UserModel;
import com.TinyBBS.util.Util;

/**
 * Servlet implementation class Register
 */
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String uri = "";
		String error = "";
		UserModel userM;
		if (request.getParameter("registersubmit") == null) {
			uri = "views/register.jsp";
		} else {
			userM = new UserModel();
			String username = request.getParameter("username").trim();
			String firstname = request.getParameter("firstname").trim();
			String lastname = request.getParameter("lastname").trim();
			String email = request.getParameter("email").trim();
			String password = request.getParameter("password").trim();
			String repeatPassword = request.getParameter("repeatpassword")
					.trim();
			if (userM.getUserByEmail(email) != null
					|| userM.getUserByUsername(username) != null) {
				error = "Your email/username is/are not availible";
				uri = "views/register.jsp";
			} else if (password.equals(repeatPassword) == false) {
				error = "Your password does not match";
				uri = "views/register.jsp";
			} else {
				User user = new User();
				Random random = new Random();
				user.setAccess_level(Config.PENDING);
				user.setEmail(email);
				user.setFirstname(firstname);
				user.setLastname(lastname);
				user.setPassword(Util.getHashWithSalt(password, Config.SALT));
				user.setStartdate(Util.getCurrentTimeStamp());
				user.setToken(Util.GenerateInteger(100000, 999999, random));
				user.setUsername(username);
				if (userM.insertUser(user)) {
					uri = "views/registerSuccess.jsp";
				} else {
					error = "Failed to register an account";
					uri = "views/register.jsp";
				}

			}
		}
		request.setAttribute("error", error);
		System.out.println();
		RequestDispatcher rd = request.getRequestDispatcher(uri);
		rd.forward(request, response);
	}

}
